#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 noet:
#
# $Id$

"""
PreviewManager.py

Handles the display of a replacement preview.
Only handles single-line replacements.
"""

__version__ = "$Revision$"
# $URL$

class PreviewManager(object):
	"""
	See module docstring.
	"""
	def __init__(self, textView):
		self._textView = textView
	
	def populate(self, document, startIter, endIter, replacement):
		"""
		Populates the preview window content from startIter.
		"""
		encoding = document.get_encoding().get_charset()
		# Get a line of context for the preview.
		lineStartIter = startIter.copy()
		lineStartIter.set_line_offset(0)
		lineEndIter = endIter.copy()
		if not lineEndIter.ends_line():
			lineEndIter.forward_to_line_end()
		line = document.get_text(lineStartIter, lineEndIter).decode(encoding)
		head = line[:startIter.get_line_offset()]
		tail = line[endIter.get_line_offset():]
		buffer = self._textView.get_buffer()
		newText = head + replacement + tail
		buffer.set_text(newText.encode(encoding))
		if replacement:
			# Highlight the preview section.
			tagTable = buffer.get_tag_table()
			highlightTag = tagTable.lookup("highlight")
			if highlightTag is not None:
				tagTable.remove(highlightTag)
			highlightTag = buffer.create_tag("highlight", background="yellow")
			previewStartIter = buffer.get_start_iter()
			startLineOffset = startIter.get_line_offset()
			previewStartIter.set_line_offset(startLineOffset)
			previewEndIter = buffer.get_start_iter()
			previewEndIter.set_line_offset(len(replacement) + startLineOffset)
			buffer.apply_tag(highlightTag, previewStartIter, previewEndIter)

	def clear(self):
		self._textView.get_buffer().set_text("")

# End of $URL$
